package com.cz.basetool.ui_work.util.time;

import android.util.Log;

import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Done on 2017/1/14.
 */

public class MyTimer {

    private Timer mTimer;

    private TimerTask mTimerTask;

    private boolean isEffective = true;

    private OverTimeListener mListener = null;

    public void setOverTimeListener(OverTimeListener mListener) {
        this.mListener = mListener;
    }

    private static final String TAG = "MyTimer";

    public void startTimer(long overtime) {
        mTimer = new Timer();

        mTimerTask = new TimerTask() {
            @Override
            public void run() {
//                AndroidConsoleLogPrinter.d(TAG, "定时任务执行... 数据失效了");
                isEffective = false;

                if (mListener != null) {
                    mListener.OnOverTime(isEffective);
                
                }
                stopTimer();
            }
        };


        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, overtime);
            AndroidConsoleLogPrinter.d("cz", "开始计算超时," + overtime + "毫秒之后");
        }


    }

    public void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        isEffective = true;
//        AndroidConsoleLogPrinter.d(TAG, "主动停止计时，数据有效:" + isEffective);
    }

    public void stopTimerRightNow() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        isEffective = true;
//        AndroidConsoleLogPrinter.d(TAG, "主动停止计时，数据有效:" + isEffective);
    }

    public boolean isEffective() {
        return isEffective;
    }

    public void setEffective(boolean effective) {
        isEffective = effective;
    }

    public interface OverTimeListener {
        /**
         * 超时接口
         *
         * @param isOverTime
         */
        void OnOverTime(boolean isOverTime);
    }
}
